package middlewares

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/jaeger"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/sdk/resource"
	tracesdk "go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.17.0"
	"go.uber.org/zap"
	"mxshop-api/goods-web/global"
)

func tracerProvider(url string) (*tracesdk.TracerProvider, error) {
	// 创建 Jaeger 导出器
	exp, err := jaeger.New(jaeger.WithCollectorEndpoint(jaeger.WithEndpoint(url)))
	if err != nil {
		return nil, err
	}
	tp := tracesdk.NewTracerProvider(
		// Always be sure to batch in production.
		tracesdk.WithBatcher(exp),
		// Record information about this application in a Resource.
		tracesdk.WithResource(resource.NewWithAttributes(
			semconv.SchemaURL,
			semconv.ServiceName(global.ServerConfig.JaegerInfo.Name),
			//attribute.String("key-czc", "Value-czc"),
			//attribute.Int64("ID", id),
		)),
	)
	return tp, nil
}

func Trace() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 用来创建 Jaeger 导出器
		tp, err := tracerProvider(fmt.Sprintf("http://%s:%d/api/traces", global.ServerConfig.JaegerInfo.Host, global.ServerConfig.JaegerInfo.Port))
		if err != nil {
			zap.S().Debug(err)
		}
		//defer func() {
		//	if err := tp.Shutdown(context.Background()); err != nil {
		//		zap.S().Debugf("关闭跟踪程序提供程序时出错: %v", err)
		//	}
		//}()

		// 将TracerProvider注册为全局，以便将来任何导入的检测都会默认使用它。
		otel.SetTracerProvider(tp)
		otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))
		_, span := otel.Tracer("sxshop-api").Start(context.Background(), ctx.Request.URL.Path)
		defer span.End()
		ctx.Next()

	}

}
